<!DOCTYPE html>

<html>
    <head>
        <meta charset="UTF-8">
        <title>阻止事件默认行为</title>
        <style>
            .wrapper { 
                padding: 10px;
                border: 1px solid blue; 
                margin: 15px auto; 
            }

            .title { margin: 0; }

            .wrapper b { 
                display: inline-block;
                padding: 5px ; 
                border: 1px solid blue; 
                margin: 10px auto;
                user-select: none;
            }
        </style>
    </head>
    <body>
        <h1>阻止事件默认行为</h1>
        <div class="wrapper">
            <p class="title">阻止超链接"点击事件"的默认行为</p>
            <a href="http://www.kaifamiao.com">开发喵</a>
            <a href="http://www.ceshiwang.com">测试汪</a>
            <a href="http://www.golianda.com">狗联达</a>
        </div>

        <div class="wrapper">
            <p class="title">阻止提交按钮"点击事件"的默认行为</p>
            <form action="http://www.baidu.com/s" method="get" class="first">
                <input type="text" name="wd">
                <input type="submit" value="百度一下">
                <button type="submit">百度一下</button>
            </form>
        </div>

        <div class="wrapper">
            <p class="title">阻止表单"提交事件"的默认行为</p>
            <form action="http://www.baidu.com/s" method="get" class="second">
                <input type="text" name="wd">
                <input type="submit" value="百度一下">
                <button type="submit">百度一下</button>
            </form>
            <b class="pseudo-button">点我试试能不能提交表单</b>
        </div>
        <p>请在浏览器终端中查看运行结果</p>
        <script>
            (()=>{

                const handler = event => {
                    event.preventDefault(); // 阻止事件的默认行为
                    console.log( event.type, event.target );
                }

                const links = document.links;
                Array.from(links).forEach( a => {
                    a.addEventListener('click', handler, false);
                });

                // 选中页面上第一个表单中所有的提交按钮
                const submits = document.querySelectorAll('.first [type=submit]');
                Array.from(submits).forEach( btn => {
                    btn.addEventListener('click', handler, false);
                });

                // document.forms 表示当前文档中所有表单组成的集合
                const form = document.forms[1];
                // 为表单绑定 submit 事件监听器
                form.addEventListener('submit', handler, false);

                const pb = document.querySelector('.pseudo-button');
                pb.addEventListener('click', evt => {
                    // 直接调用 form.submit() 方法时，submit事件不会发送到表单
                    form.submit();// 通过调用函数来提交表单
                }, false);
            })();
        </script>
    </body>
</html>